package com.xdhl.fu.fim.xxljob.job;

import com.xdhl.fu.common.core.constant.flightinfo.FlightInfoConstants;
import com.xdhl.fu.common.core.task.IJob;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 美元兑换人民币汇率执行者
 *
 * @author 朱力维
 * @time 2022/6/2 12:55
 */
@Component
public class DollarsToCNYuanRateJob implements IJob {

    private static final Logger log = LoggerFactory.getLogger(DollarsToCNYuanRateJob.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final String URI = "https://www.huilv.cc/";

    public static void main(String[] args) {
        try {
            Document document = Jsoup.connect(URI).get();
            Elements elements = document.select("#main .back");
            System.out.println(elements.get(0).text());
        } catch (IOException e) {
            // nothing to do
        }
    }

    @Transactional
    @XxlJob(value = "dollarsToCNYuanRateJob", init = "init", destroy = "destroy")
    public ReturnT<String> execute(String param) {
        this.start();
        log.info("美元兑换人民币汇率已更新完成。");
        return ReturnT.SUCCESS;
    }

    @Override
    public void start() {
        try {
            Document document = Jsoup.connect(URI).get();
            Elements elements = document.select("#main .back");
            String rate = elements.get(0).text();

            stringRedisTemplate.opsForValue().set(FlightInfoConstants.DOLLARS_TO_CNYUAN_RATE, rate.trim());
        } catch (IOException e) {
            // nothing to do
        }
    }

    @Override
    public void init() {

    }

    @Override
    public void destroy() {

    }

}
